<template>
    <el-dropdown trigger="click" class="international" @command="handleSetTheme">
        <div>
            <svg-icon name="top_theme" />
        </div>
        <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="(item, index) of themeOptions" :key="index" :command="item" class="">
                <div :class="item.value === selectTheme ? 'active' : ''" class="theme-item">
                    <span>{{ item.label }}</span>
                    <el-button type="text" size="small" class="mgl-10" icon="el-icon-close" @click.stop="deleteItem(item)" />
                </div>
            </el-dropdown-item>
        </el-dropdown-menu>
    </el-dropdown>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import apiUrl from '@/api/customer-theme';
import { Dictionary } from 'vue-router/types/router';
interface ThemeOptionsConfig {
    label: string;
    value: string;
    customerThemeMap: Dictionary<string>;
    cssLink: any[];
    // themeId: string
}
@Component({
    name: 'theme'
})
export default class extends Vue {
    private themeOptions: ThemeOptionsConfig[] = [];
    selectTheme: string = '';
    private async handleSetTheme(obj: any) {
        const heads = document.getElementsByTagName('head');
        const elementurl = document.getElementsByClassName('elementurl');
        const styleFileName = document.getElementsByClassName('styleFileName');
        if (obj.cssLink.length <= 0) {
            if (elementurl.length > 0 || styleFileName.length > 0) {
                heads[0].removeChild(elementurl[0]);
                heads[0].removeChild(styleFileName[0]);
            }
            return;
        }

        const res = await this._put({
            url: apiUrl.selectTheme,
            params: {
                userId: this.$store.state.user.userId,
                themeId: obj.value
            }
        });
        if (res.code === 0) {
            this._message({ message: '设置主题成功', type: 'warning' });
            this.setThemeConfig(obj);
        }
    }
    setThemeConfig(obj) {
        this.selectTheme = obj.value;
        Object.keys(obj.customerThemeMap).forEach((key) => {
            this.$store.dispatch('settings/changeThemeSetting', {
                key: key,
                value: obj.customerThemeMap[key]
            });
        });
        obj.cssLink.forEach((item) => {
            this.getThemeFileFn(item);
        });
    }
    async deleteItem(item) {
        const res = await this._post({
            url: apiUrl.removeTheme,
            data: {
                data: [item.value],
                NetNeedModuleId: true
            }
        });
        if (res.code === 0) {
            this._message({ message: '删除成功', type: 'warning' });
            this.getThemeList();
        }
    }
    getThemeFileFn(obj) {
        const linkDom = document.getElementsByClassName(obj.name);
        if (linkDom.length > 0) {
            if (obj.name === 'styleFileName') {
                linkDom[0].innerHTML = obj.customerJson;
            } else {
                linkDom[0].setAttribute('href', obj.url);
            }
            return;
        }
        let link: any = null;
        if (obj.name === 'styleFileName') {
            link = document.createElement('style');
            link.setAttribute('class', obj.name);
            link.innerHTML = obj.customerJson;
        } else {
            link = document.createElement('link');
            link.setAttribute('class', obj.name);
            link.setAttribute('rel', 'stylesheet');
            link.setAttribute('type', 'text/css');
            link.setAttribute('href', obj.url);
        }
        const head = document.getElementsByTagName('HEAD').item(0)!;
        head.appendChild(link);
    }
    getThemeList() {
        this._post({ url: apiUrl.findThemeList }).then((res) => {
            const data = res.data || [];
            this.themeOptions = data.map((item) => {
                return this.formatThemeOptions(item);
            });
        });
    }
    formatThemeOptions(item): ThemeOptionsConfig {
        const newObj: ThemeOptionsConfig = {
            label: item.themeName,
            value: item.id,
            customerThemeMap: item.customParamMap,
            cssLink: [
                {
                    name: 'elementurl',
                    url: item.elementurl
                },
                {
                    name: 'styleFileName',
                    customerJson: item.customJson,
                    url: item.styleUrl
                }
            ]
        };
        return newObj;
    }
    async getSelectTheme() {
        const res = await this._post({
            url: apiUrl.findUserTheme,
            data: {
                data: this.$store.state.user.userId,
                NetNeedModuleId: true
            }
        });
        if (res.code === 0 && res.data) {
            const item = this.formatThemeOptions(res.data || []) || {};
            this.setThemeConfig(item);
        }
    }
    mounted() {
        this.$nextTick(() => {
            this.getThemeList();
            this.getSelectTheme();
        });
    }
}
</script>
<style scoped lang="scss">
@import 'src/styles/variables.scss';

.active {
    color: $basic;
}
.theme-item {
    min-width: 80px;
    display: flex;
    justify-content: space-between;
}
</style>
